package deng.camel.examples;

import java.util.concurrent.CountDownLatch;

import javax.naming.NamingException;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.util.jndi.JndiContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import deng.camel.beans.processors.ExchangeLogger;

public class FilePollerDemo extends RouteBuilder {
	
	private static Log logger = LogFactory.getLog(FilePollerDemo.class);
	
	public static void main(String[] args) {
		new FilePollerDemo().start();
	}
	
	private CountDownLatch latch = new CountDownLatch(1);
	private DefaultCamelContext camelContext;
	private JndiContext beanRegistry;
	private Processor countDownLatchProcessor;
	
	public void start() {
		try {
			countDownLatchProcessor = new CountDownLatchProcessor();
			beanRegistry = new JndiContext();
			camelContext = new DefaultCamelContext(beanRegistry);
			camelContext.addRoutes(this);
			beforeCamelStart();
			camelContext.start();
			afterCamelStart();
			latch.await();
			camelContext.stop();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}		
	}

	private void beforeCamelStart() {
		try {
			beanRegistry.bind("exchangeLogger", new ExchangeLogger());
		} catch (NamingException e) {
			throw new RuntimeException(e);
		}
	}

	private void afterCamelStart() {
	}

	@Override
	public void configure() throws Exception {
		from("file:///D:/camel-poll-dir?noop=true") // noop=do not delete file
			.to("bean:exchangeLogger")
			.process(countDownLatchProcessor);
	}
	
	private class CountDownLatchProcessor implements Processor {
		@Override
		public void process(Exchange exchange) throws Exception {
			logger.trace("Count down latch");
			latch.countDown();
		}				
	}

}
